package com.fly.show.docker;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spotify.docker.client.messages.Container;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
public class PushDockerJob
{
    String last = "";
    
    @Autowired
    DockerService dockerService;
    
    ObjectMapper objectMapper = new ObjectMapper();
    
    @Scheduled(cron = "0/5 * * * * ?")
    public void run()
    {
        try
        {
            // 变化才推送
            List<Container> containers = dockerService.getContainers();
            String message = objectMapper.writeValueAsString(containers);
            
            //TODO：实际测试不可行Container的Ports、Mounts部分转换为字符串后，顺序不稳定
            if (!StringUtils.equals(last, message))
            {
                log.info("###### pushData again");
                SSEServer.batchSendMessage(message);
                last = message;
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
